package com.jinbai.servlet.album;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jinbai.util.DBUtil;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/studio/album/published.json")
public class PublishedJsonServlet extends HttpServlet {
    private static class ResultView {
        public Integer aid;
        public String cover;
        public String title;
        public Integer uid;
        public String username;

        public ResultView(int aid, String cover, String title, int uid, String username) {
            this.aid = aid;
            this.cover = cover;
            this.title = title;
            this.uid = uid;
            this.username = username;
        }
    }
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        List<ResultView> resultViewList = new ArrayList<>();
        try (Connection con = DBUtil.connection()) {
            String sql = "select aid, cover, title, a.uid, username from albums a join users u on a.uid = u.uid where state = 2";
            try (PreparedStatement ps = con.prepareStatement(sql)) {
                try (final ResultSet rs = ps.executeQuery()) {
                    while (rs.next()) {
                        resultViewList.add(new ResultView(rs.getInt("aid"),
                                                                rs.getString("cover"),
                                                                rs.getString("title"),
                                                                rs.getInt("uid"),
                                                                rs.getString("username")));
                    }
                }
            }
        }
        ObjectMapper objectMapper = new ObjectMapper();
        final String json = objectMapper.writeValueAsString(resultViewList);
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().println(json);
    }
}
